package com.imdroid.carac.speechRecog;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviPara;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;
import com.imdroid.carac.activities.HomeActivity;
import com.imdroid.carac.activities.NavigatorPointSetting;
import com.imdroid.carac.activities.RecordActivity;
import com.imdroid.carac.activities.TeamSelectActivity;
import com.imdroid.carac.model.Destination;

import edu.cmu.pocketsphinx.Hypothesis;

public class SpeechRecog {

	
	
	
private static boolean running = false;

private static List<String> availableWords = new ArrayList<String>();
static {
//	Log.e( "TTT", "TTT" );
	// 检查存储卡里面的语音数据，没有的话复制好
	InputStream in = IMDroid.getContext().getResources()
			.openRawResource(R.raw.speech_recog);
	unZip(in, IMDroid.SPEECH_RECOG_FOLDER);
	
	BufferedReader raf;
	try {
		raf = new BufferedReader( new InputStreamReader( new FileInputStream( IMDroid.SPEECH_RECOG_FOLDER+"A.dic" ) ) );
	} catch( FileNotFoundException e1 ) {
		throw new RuntimeException( e1 );
	}
	while( true ) {
		String line;
		try {
			line = raf.readLine();
		} catch( IOException e ) {
			throw new RuntimeException( e );
		}
		if( line == null )
			break;
		line = line.trim();
		if( line.equals( "" ) )
			break;
		availableWords.add( line.split( "\\s" )[0] );
//		Log.e( "AAA", availableWords.get( availableWords.size()-1 ) );
	}
	// 准备好相关线程
	SpeechRecogThread.init();
}

public static void init() {
}

public static void go() {
	if (running)
		return;
	running = true;
	MediaPlayer mp = MediaPlayer.create(IMDroid.getContext(),
			R.raw.tip_ding_dong);
	mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
		public void onCompletion(MediaPlayer mp) {
			mp.release();
		}
	} );
	mp.start();

	IMDroid.runInMainLooper(mp.getDuration() - 600, new Runnable() {
		public void run() {
			SpeechRecogThread.start();
			SpeechRecogDialog.start();
		}
	} );
}

static void onStop() {
	running = false;

	Hypothesis hypothesis = SpeechRecogThread.stop();
	String result = null;
	if (hypothesis != null)
		result = hypothesis.getHypstr();
	if (result == null)
		result = "";
	result = result.trim();

	String s = null;
	for( String word : availableWords )
		if( result.startsWith(word) ) {
			s = word;
			break;
		}
	if( s == null ) {
		Toast.makeText(IMDroid.getContext(),
				IMDroid.getContext().getString(R.string.home_cannot_recog),
				Toast.LENGTH_SHORT).show();
		return;
	}
	Toast.makeText(IMDroid.getContext(), "语音识别--" + result+"--"+s, Toast.LENGTH_SHORT).show();
	result = s;

	AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.getInstance());
	builder.setMessage(result + " ？");
	final String finalResult = result;
	builder.setPositiveButton("是", new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// 用户认为识别正确
			dialog.dismiss();
			onConfirmed(finalResult);
		}
	} );
	builder.setNegativeButton("否", new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// 用户认为识别错误
			dialog.dismiss();
		}
	} );
	builder.create().show();
}

private static void sendKey( int keyCode ) {
    try {
		Runtime.getRuntime().exec( "input keyevent " + keyCode );
	} catch (IOException e) {
		throw new RuntimeException( e );
	}
}

private static void onConfirmed(String result) {
	if( result.equals("导航") ) {
//		IMDroid.getContext().startActivity(new Intent(IMDroid.getContext(), TeamSelectActivity.class));
		HomeActivity.getInstance().startActivity(new Intent(IMDroid.getContext(),
				NavigatorPointSetting.class));
		
	} else if( result.equals("上班") ) {
		launchNavigator("company");
		
	} else if( result.equals("回家") ) {
		launchNavigator("home");
		
	} else if ( result.equals("组队") ) {
		Intent in = new Intent(HomeActivity.getInstance(), TeamSelectActivity.class);
		in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		HomeActivity.getInstance().startActivity(in);
		
	} else if ( result.equals("录像") ) {
//		IMDroid.runInMainLooper(  )
		HomeActivity.getInstance().startActivity(new Intent(HomeActivity.getInstance(), RecordActivity.class));
		
	} else if ( Arrays.asList("退出".split("\\s")).contains(result) ) {
		sendKey( KeyEvent.KEYCODE_BACK );
		
	} else if ( Arrays.asList("主页 主菜单 首页 第一页".split("\\s")).contains(result) ) {
		HomeActivity.getInstance().startActivity(new Intent(HomeActivity.getInstance(), HomeActivity.class));
		
	} else if ( Arrays.asList("音量大 音量增加 音量加".split("\\s")).contains(result) ) {
		sendKey( KeyEvent.KEYCODE_VOLUME_UP );

	} else if ( Arrays.asList("音量小 音量减小 音量减".split("\\s")).contains(result) ) {
		sendKey( KeyEvent.KEYCODE_VOLUME_DOWN );

	} else if ( Arrays.asList("确认".split("\\s")).contains(result) ) {
		sendKey( KeyEvent.KEYCODE_SPACE );

	} else {
	}
}

private static void launchNavigator(String addressName) {
	Destination d = Destination.getDestination(addressName);
	if (d != null) {
		BDLocation currentLocation = IMDroid.getCurrentLocation();
		if (currentLocation == null) {
			Toast.makeText(IMDroid.getContext(),
					IMDroid.getContext().getString(R.string.loc_error_no_gps_wait),
					Toast.LENGTH_LONG).show();
			return;
		}

		double mLat1 = currentLocation.getLatitude();
		double mLon1 = currentLocation.getLongitude();
		double mLat2 = d.getLatitude();
		double mLon2 = d.getLongitude();
		int lat = (int) (mLat1 * 1E6);
		int lon = (int) (mLon1 * 1E6);
		GeoPoint pt1 = new GeoPoint(lat, lon);
		lat = (int) (mLat2 * 1E6);
		lon = (int) (mLon2 * 1E6);
		GeoPoint pt2 = new GeoPoint(lat, lon);

		NaviPara para = new NaviPara();
		para.startPoint = pt1; // 起点坐标
		para.startName = IMDroid.getContext().getString(R.string.loc_map_loc);
		para.endPoint = pt2; // 终点坐标
		para.endName = d.getAddress();
		System.out.println(mLat1 + " " + mLat2);

		try {
			BaiduMapNavigation.openBaiduMapNavi(para,
					HomeActivity.getInstance());
		} catch (BaiduMapAppNotSupportNaviException e) {
			// 在此处理异常
			e.printStackTrace();
		}
		// Intent intent = new Intent(Intent.ACTION_VIEW);
		// Uri uri = Uri.parse("geo:" + d.getLatitude() + ","
		// + d.getLongitude() + "?q=" + d.getAddress());
		// intent.setData(uri);
		// intent.setPackage("com.baidu.BaiduMap");
		// context.startActivity(intent);
	} else {
		String text = IMDroid.getContext().getString(R.string.loc_address_not_set);
		Toast.makeText(IMDroid.getContext(), text, Toast.LENGTH_SHORT).show();
	}
}

private static void unZip(InputStream zipFileIn, String toPath) {
	ZipInputStream in = null;
	FileOutputStream out = null;
	try {

		byte buf[] = new byte[100 * 1024];
		in = new ZipInputStream(new BufferedInputStream(zipFileIn));
		for (ZipEntry zipEntry = null; (zipEntry = in.getNextEntry()) != null;) {
			File file = new File(toPath, zipEntry.getName());

			if (zipEntry.isDirectory()) {
				file.mkdirs();
				continue;
			}

			if (file.isDirectory())
				throw new RuntimeException("" + file);

			if (file.isFile() && zipEntry.getSize() == file.length()
					&& zipEntry.getTime() == file.lastModified())
				continue;

			File parent = file.getParentFile();
			if (!parent.exists())
				parent.mkdirs();
			out = new FileOutputStream(file);
			for (int n = 0; (n = in.read(buf)) > 0;)
				out.write(buf, 0, n);
			out.close();
			out = null;
			file.setLastModified(zipEntry.getTime());
			in.closeEntry();
		}

	} catch (IOException e) {
		throw new RuntimeException(e);

	} finally {
		try {
			if (in != null)
				in.close();
			if (out != null)
				out.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}




}
